//
//  MovieHomePageVC.m
//  彩虹儿歌
//
//  Created by HelloWorld_L on 15/6/30.
//  Copyright (c) 2015年 HelloBaby. All rights reserved.
//

#import "MovieHomePageVC.h"
#import "MacroHeader.h"
#import "RequestManager.h"
#import "HPVCModel.h"
#import <UIImageView+WebCache.h>
#import "HPCollectionViewCell.h"
#import "HPCarouselColleVCell.h"
#import "ListViewController.h"
#import "StyledPageControl.h"
@interface MovieHomePageVC ()<UIScrollViewDelegate,RequestDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

@property (nonatomic, retain) RequestManager *request1;//轮播图
@property (nonatomic, retain) RequestManager *request2;//collectionView

@property (nonatomic, retain) UIScrollView *carouselCScrollV;
@property (nonatomic, retain) StyledPageControl *pageControl;
@property (nonatomic, retain) NSMutableArray *carouselCDataArr;
@property (nonatomic, retain) NSTimer *timer;

@property (nonatomic, retain) UICollectionView *mainCollectionV;
@property (nonatomic, retain) NSMutableArray *collectionVDataArr;

@end

@implementation MovieHomePageVC

- (void)dealloc
{
    [_request1.delegate release];
    [_request1 release];
    [_request2.delegate release];
    [_request2 release];
    [_carouselCScrollV release];
    [_pageControl release];
    [_carouselCDataArr release];
    [_timer release];
    [_mainCollectionV release];
    [_collectionVDataArr release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    UIImageView *backgroundImgV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"xiaohua01"]];
    [self.view addSubview:backgroundImgV];
    
    self.navigationController.navigationBarHidden = NO;
    self.carouselCDataArr = [NSMutableArray array];
    self.collectionVDataArr = [NSMutableArray array];
    [self requestData1];
    [self requestData2];
    [self addTimer];
    [self createCollectionV];
    
}

- (void)createCollectionV
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumInteritemSpacing = 8;
    flowLayout.minimumLineSpacing = 10;
    self.mainCollectionV = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 60) collectionViewLayout:flowLayout];
    self.mainCollectionV.backgroundColor = [UIColor clearColor];
    self.mainCollectionV.delegate = self;
    self.mainCollectionV.dataSource = self;
    
    [self.mainCollectionV registerClass:[HPCarouselColleVCell class] forCellWithReuseIdentifier:@"HPCarouselColleVCell"];
    [self.mainCollectionV registerClass:[HPCollectionViewCell class] forCellWithReuseIdentifier:@"HPCollectionViewCell"];
    
    [self.view addSubview:self.mainCollectionV];
    [flowLayout release];
    [self.mainCollectionV release];
    
}

#pragma mark - UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        CGSize size = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT / 4);
        return size;
    } else {
        CGSize size = CGSizeMake((SCREEN_WIDTH - 30) / 2, (SCREEN_WIDTH - 30) / 2);
        return size;
    }
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    } else {
        return  self.collectionVDataArr.count + 1;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        HPCarouselColleVCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HPCarouselColleVCell" forIndexPath:indexPath];
        cell.carouselCScrollV.delegate = self;
        [cell setcarcouselWithArr:self.carouselCDataArr];
        self.carouselCScrollV = cell.carouselCScrollV;
        self.pageControl = cell.pageControl;
        return cell;
    } else {
        HPCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HPCollectionViewCell" forIndexPath:indexPath];
        if (indexPath.item == 0) {
            cell.coverImgV.image = [UIImage imageNamed:@"waxingren"];
            cell.titleLab.text = @"最近播放";

            return cell;
        } else {
            HPVCModel *model = self.collectionVDataArr[indexPath.item - 1];
            cell.model = model;

            return cell;
        }
    }
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    if (section == 0) {
        UIEdgeInsets ei = UIEdgeInsetsMake(0, 0, 0, 0);
        return ei;
    } else {
        UIEdgeInsets ei = UIEdgeInsetsMake(10, 10, 10, 10);
        return ei;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            return;
        } else {
            ListViewController *listVC = [[ListViewController alloc] init];
            listVC.plistId = [[self.collectionVDataArr[indexPath.row - 1] item_info] objectForKey:@"playlist_id"];
            listVC.naviBarItemTitle = [self.collectionVDataArr[indexPath.row - 1] recommend_title];
            [self.navigationController pushViewController:listVC animated:YES];
            [listVC release];
        }
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    if (section == 1) {
        CGSize size = CGSizeMake(0, 50);
        return size;
    } else {
        return CGSizeZero;
    }
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == self.carouselCScrollV) {
        self.pageControl.currentPage = self.carouselCScrollV.contentOffset.x / SCREEN_WIDTH;
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
        [self addTimer];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
        [self removeTimer];
}

#pragma mark - NSTimer
- (void)addTimer
{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:3.5 target:self selector:@selector(nextImage) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)removeTimer
{
    [self.timer invalidate];
}

- (void)nextImage
{
    
    if (self.pageControl.currentPage == self.carouselCDataArr.count - 1) {
        self.pageControl.currentPage = 0;
        
        self.carouselCScrollV.contentOffset = CGPointMake(self.pageControl.currentPage * SCREEN_WIDTH, 0);

    } else {
        if ([self.carouselCScrollV subviews].count == 6) {//为了安全，避免网速慢图片未加载完全导致奔溃。
            
            CATransform3D rotate1 = CATransform3DMakeRotation(M_PI / 2, 0, 1, 0);//90
            CATransform3D rotate2 = CATransform3DMakeRotation(-(M_PI / 2), 0, 1, 0);//-90
            CATransform3D rotate3 = CATransform3DMakeRotation(0, 0, 1, 0);//0
            
            self.pageControl.currentPage++;
            
            UIView *imageV =  (UIView *)([self.carouselCScrollV subviews][self.pageControl.currentPage]);
            UIView *imageV2 =  (UIView *)([self.carouselCScrollV subviews][self.pageControl.currentPage + 1]);
            
            imageV.layer.transform = CATransform3DPerspect(rotate3, CGPointMake(0, 0), 300);
            imageV2.layer.transform = CATransform3DPerspect(rotate2, CGPointMake(0, 0), 300);
            [UIView animateWithDuration:2 animations:^{
                self.carouselCScrollV.contentOffset = CGPointMake(self.pageControl.currentPage * SCREEN_WIDTH, 0);
                
                imageV.layer.transform = CATransform3DPerspect(rotate1, CGPointMake(0, 0), 300);
                imageV2.layer.transform = CATransform3DPerspect(rotate3, CGPointMake(0, 0), 300);
                
            } completion:^(BOOL finished) {
                
                imageV.layer.transform = CATransform3DPerspect(rotate3, CGPointMake(0, 0), -300);
                
            }];
            
        } else {
            
            [self.mainCollectionV reloadData];
            
        }
    }
}

CATransform3D CATransform3DMakePerspective(CGPoint center, float disZ)
{
    CATransform3D transToCenter = CATransform3DMakeTranslation(-center.x, -center.y, 0);
    CATransform3D transBack = CATransform3DMakeTranslation(center.x, center.y, 0);
    CATransform3D scale = CATransform3DIdentity;
    scale.m34 = -1.0f/disZ;
    return CATransform3DConcat(CATransform3DConcat(transToCenter, scale), transBack);
}

CATransform3D CATransform3DPerspect(CATransform3D t, CGPoint center, float disZ)
{
    return CATransform3DConcat(t, CATransform3DMakePerspective(center, disZ));
}

#pragma mark - 请求数据
- (void)requestData1//轮播图
{
    self.request1 = [[RequestManager alloc] initWithRequestURL:@"http://app.beva.com/box-recommend/pkg46/dcios--kwerge--v2.0.json" requestModel:GET parameter:nil];
    self.request1.delegate = self;
    [self.request1 startRequest];
    [self.request1 release];
}

- (void)requestData2//collectionView
{
    self.request2 = [[RequestManager alloc] initWithRequestURL:@"http://app.beva.com/box-recommend/pkg46/dciosHot--kwerge--v2.0.json" requestModel:GET parameter:nil];
    self.request2.delegate = self;
    [self.request2 startRequest];
    [self.request2 release];
}

- (void)requestDidFinishWithData:(NSData *)data
{
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
    NSArray *carouselCArr = dic[@"data"];
    
    if ([dic[@"data"][0][@"recommend_title"] isEqualToString:@"最受欢迎"]) {
        for (NSDictionary *modelDic in carouselCArr) {
            HPVCModel *model = [[HPVCModel alloc] init];
            [model setValuesForKeysWithDictionary:modelDic];
            [self.collectionVDataArr addObject:model];
            [model release];
        }
    } else {
        for (NSDictionary *modelDic in carouselCArr) {
            HPVCModel *model = [[HPVCModel alloc] init];
            [model setValuesForKeysWithDictionary:modelDic];
            [self.carouselCDataArr addObject:model];
            [model release];
        }
    }
    [self.mainCollectionV reloadData];
}

- (void)requestError:(NSError *)error
{
    NSLog(@"%@",error);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
